package cn.micai.base.thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/7 18:06
 */
public class FutureTaskMain {

    public static void main(String [] args) {

        MultiplyingTask multiplyingTask1 = new MultiplyingTask(10, 20, 2000);
        MultiplyingTask multiplyingTask2 = new MultiplyingTask(12, 23, 4000);

        FutureTask<Integer> futureTask1 = new FutureTask<Integer>(multiplyingTask1);
        FutureTask<Integer> futureTask2 = new FutureTask<Integer>(multiplyingTask2);

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.execute(futureTask1);
        executorService.execute(futureTask2);

        // 无限循环
        while (true) {
            try {
                if (!futureTask1.isDone()) {
                    System.out.println("FutureTask1 output=" + futureTask1.get());
                }
                if (!futureTask2.isDone()) {
                    System.out.println("Waitng for futureTask2 for completion");
                    System.out.println("FutureTask2 output=" + futureTask2.get());
                }
                if (futureTask1.isDone() && futureTask2.isDone()) {
                    System.out.println("Completed both the FutureTasks, shutting down the executors");
                    executorService.shutdown();
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
